import { dateTimeRangeToStrRange, strToDate, encrypt } from 'utils'

export function toAppResult(res) {
  const { status, data, message, timestamp } = res
  return {
    code: status,
    data: data,
    msg: message,
    ts: timestamp
  }
}

export function toPageParam({ currentPage, pageSize }) {
  return {
    page: currentPage,
    size: pageSize
  }
}

export function toPageResult(data) {
  const { content, totalElements } = data
  return {
    rows: content,
    total: totalElements
  }
}

export function toRangeParam(
  data,
  field = 'range',
  startField = 'start',
  endField = 'end'
) {
  const res = { ...data }
  delete res[field]
  const range = data[field]
  if (range && range.length > 0) {
    const [start, end] = dateTimeRangeToStrRange(range)
    res[startField] = start
    res[endField] = end
  }
  return res
}

export function fromRangeParam(
  data,
  field = 'range',
  startField = 'start',
  endField = 'end'
) {
  if (!data) {
    return null
  }
  const res = { ...data }
  const start = strToDate(data[startField])
  const end = strToDate(data[endField])
  delete res[startField]
  delete res[endField]
  const range = [start, end]
  res[field] = range
  return res
}

export function toPasswordParam(data, field = 'password') {
  const res = { ...data }
  delete res[field]
  res[field] = encrypt(data[field])
  return res
}

export function toAreaParam(
  data,
  areaField = 'area',
  provinceField = 'province',
  cityField = 'city',
  countyField = 'county'
) {
  const res = { ...data }
  delete res[areaField]
  const area = data[areaField]
  if (area && area.length > 0) {
    const [province, city, county] = area
    res[provinceField] = province
    res[cityField] = city
    res[countyField] = county
  }
  return res
}
